<template>
  <a-card :bordered="false">
    <div ref="crudContentRef">
      <a-button type="primary" @click="openAddPopup">創建角色</a-button>
      <a-table
        :loading="loading"
        :scroll="{ x: '100%', y: '100%' }"
        :columns="columns"
        :pagination="false"
        :data="data">
        <template #ctime="{ record }">
          {{ dateFormat(record.ctime) }}
        </template>
        <template #lastLoginTime="{ record }">
          {{ dateFormat(record.lastLoginTime) }}
        </template>
        <template #optional="{ record }">
          <a-link v-auth="[1, 2]" @click="passwordPopupOpen(record)"> 修改密碼 </a-link>
          <a-link
            v-auth="[1, 2]"
            :status="record.status == 1 ? 'danger' : 'success'"
            @click="changeAdminStatus(record)">
            {{ record.status == 1 ? '禁用' : '啟用' }}
          </a-link>
        </template>
      </a-table>
    </div>
    <a-modal
      v-model:visible="visible"
      title="添加角色"
      width="600px"
      :ok-loading="btnLoading"
      @cancel="close"
      @before-ok="submit">
      <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
        <a-form-item label="帳號" field="username">
          <a-input v-model="formData.username" placeholder="請輸入帳號" />
        </a-form-item>
        <a-form-item label="密碼" field="password">
          <a-input v-model="formData.password" placeholder="請輸入密碼" />
        </a-form-item>
        <a-form-item label="權限" field="roleType">
          <a-radio-group v-model="formData.roleType" type="button">
            <a-radio :value="1">高級管理員</a-radio>
            <a-radio :value="2">普通管理員</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="visiblePassword"
      title="修改密碼"
      width="400px"
      :ok-loading="btnLoading"
      @cancel="closePassword"
      @before-ok="submitPassword">
      <a-form ref="formRef2" :model="formData2" :rules="rules2" :auto-label-width="true">
        <a-form-item label="密碼" field="newPassword">
          <a-input v-model="formData2.newPassword" placeholder="請輸入新密碼" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import adminApi from '@/api/admin'
import tool from '@/utils/tool'

const pageObj = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const loading = ref(false)
const btnLoading = ref(false)
const visible = ref(false)
const visiblePassword = ref(false)
const columns = ref([
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '帳號',
    dataIndex: 'username',
  },
  {
    title: '權限',
    dataIndex: 'roleName',
  },
  {
    title: '當前狀態',
    dataIndex: 'statusName',
    align: 'center',
  },
  {
    title: '創建時間',
    dataIndex: 'ctime',
    slotName: 'ctime',
  },
  {
    title: '最後登錄時間',
    dataIndex: 'lastLoginTime',
    slotName: 'lastLoginTime',
  },
  {
    title: '操作',
    slotName: 'optional',
  },
])

const formRef = ref()
const formRef2 = ref()
const formData = ref({
  username: '',
  password: '',
  roleType: 1,
})
const formData2 = ref({
  newPassword: '',
})
const rules = {
  username: [{ required: true, message: '帳號不能為空' }],
  password: [{ required: true, message: '密碼不能為空' }],
}
const rules2 = {
  newPassword: [{ required: true, message: '密碼不能為空' }],
}
const openAddPopup = () => {
  visible.value = true
  btnLoading.value = false
  formData.value = {
    username: '',
    password: '',
    roleType: 1,
  }
}
const close = () => {
  visible.value = false
  btnLoading.value = false
}
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (!validate) {
    btnLoading.value = true
    try {
      await adminApi.createAdmin(formData.value)
      close()
      Message.success(`添加成功！`)
      init()
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  }
  done(false)
}
const closePassword = () => {
  visiblePassword.value = false
  btnLoading.value = false
  formData2.value = {
    newPassword: '',
  }
}
const submitPassword = async (done) => {
  const validate = await formRef2.value?.validate()
  if (!validate) {
    btnLoading.value = true
    try {
      await adminApi.changeAdminPassword(clickItem.value.id, formData2.value)
      closePassword()
      Message.success(`修改成功！`)
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  }
  done(false)
}
const clickItem = ref({})
const passwordPopupOpen = (row) => {
  clickItem.value = row
  closePassword()
  visiblePassword.value = true
}
const changeAdminStatus = async (row) => {
  loading.value = true
  try {
    await adminApi.changeAdminStatus(row.id, {
      status: row.status === 0 ? 1 : 0,
    })
    loading.value = false
    row.status = row.status === 0 ? 1 : 0
    row.statusName = row.status === 0 ? '禁用' : '啟用'
    Message.success(`修改成功！`)
  } catch (error) {
    loading.value = false
  }
}
const getAdminDetail = async (row) => {
  loading.value = true
  try {
    const res = await adminApi.getAdminDetail(row.id)
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}
const data = ref([])

const pageSizeChangeHandler = async (pageSize) => {
  pageObj.page = 1
  pageObj.pageSize = pageSize
  init()
}
const pageChangeHandler = async (currentPage) => {
  pageObj.page = currentPage
  init()
}

const init = async () => {
  const res = await adminApi.getAdminList()
  data.value = res.data
}
init()

const crudContentRef = ref()
onMounted(async () => {
  await nextTick(() => {
    window.addEventListener('resize', settingFixedPage, false)
    settingFixedPage()
  })
})
const settingFixedPage = () => {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight
  let tableHeight = workAreaHeight - 24 - 24
  if (crudContentRef.value) {
    crudContentRef.value.style.height = tableHeight + 'px'
  }
}
const dateFormat = computed(() => {
  return (val) => {
    if (!val) return '-'
    return tool.dateFormat(val)
  }
})
</script>
